package com.cfweb.controller.app;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cfweb.controller.LoginHandler;
import com.cfweb.dao.AppTemplateMapper;
import com.cfweb.dao.CfAuditMapper;
import com.cfweb.dao.CfAuditServiceMapper;
import com.cfweb.dao.CfEnvironmentMapper;
import com.cfweb.dao.CfServiceInstanceMapper;
import com.cfweb.dao.CfServiceMapper;
import com.cfweb.dao.TemSerMapper;
import com.cfweb.domain.AppTemplate;
import com.cfweb.domain.CfAudit;
import com.cfweb.domain.CfAuditExternal;
import com.cfweb.domain.CfAuditService;
import com.cfweb.domain.CfAuditServiceTemp;
import com.cfweb.domain.CfEnvironment;
import com.cfweb.domain.CfService;
import com.cfweb.domain.TemSer;
import com.cfweb.domain.TemSerExample;
import com.cfweb.form.UploadAppForm;
import com.cfweb.util.ExtJSResponse;

@Service
@Path("/audit")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class AuditManagement {
	/**
	 * Logger
	 */
	private Logger logger = Logger.getLogger(AuditManagement.class);
	/**
	 * session
	 */
	@Autowired
	private HttpSession session;
	/**
	 * mapper
	 */
	@Autowired
	private CfAuditMapper cfAuditMapper;

	/**
	 * 模板服务
	 */
	@Autowired
	private TemSerMapper tsMapper;
	/**
	 * 应用模板
	 */
	@Autowired
	private AppTemplateMapper atMapper;

	@Autowired
	private CfServiceInstanceMapper cfServiceInstanceMapper;
	@Autowired
	private CfAuditServiceMapper cfAuditServiceMapper;
	/**
	 * 服务
	 */
	@Autowired
	private CfServiceMapper csMapper;
	/**
	 * buildpack
	 */
	@Autowired
	private CfEnvironmentMapper ceMapper;

	@Path("/listall")
	@GET
	public ExtJSResponse listall() throws Exception {
		String org = (String) session.getAttribute(LoginHandler.ORG);
		String space = (String) session.getAttribute(LoginHandler.SPACE);
		List<CfAuditExternal> result = cfAuditMapper.getByOrgAndSpace(org, space);
		logger.info(result.size());
		return ExtJSResponse.successResWithData(result);
	}

	@Path("/create")
	@POST
	@Consumes("multipart/form-data")
	public ExtJSResponse add(MultipartFormDataInput dataInput) throws Exception {
		/*
		 * CfAudit cfAudit = new CfAudit(); cfAudit.setDate(new Date());
		 * cfAudit.setState(0); cfAudit.setOrg(orgName);
		 * cfAudit.setSpace(spaceName); // TODO 需要更改uuid，从session获取
		 * cfAudit.setUserId((String)
		 * session.getAttribute(LoginHandler.USERID));
		 * cfAudit.setTemplateId(Integer.valueOf(templateId));
		 * cfAudit.setInstance(Integer.valueOf(instance));
		 * cfAudit.setMemory(Integer.valueOf(memory));
		 * cfAudit.setReason(reason); cfAuditMapper.insertSelective(cfAudit);
		 */
		try {
			UploadAppForm form = new UploadAppForm(dataInput);
			// 插入audit
			CfAudit cfAudit = new CfAudit(form.getAppName(), Integer.valueOf(form.getEnvId()), form.getDomains(),
					form.getFile().getAbsolutePath(), Integer.valueOf(form.getInstances()),
					Integer.valueOf(form.getMemory()), form.getOrgName(), form.getSpaceName(), form.getTemId(),
					(String) session.getAttribute(LoginHandler.USERID), 0, new Date(), "");
			cfAuditMapper.insertSelective(cfAudit);

			Integer id = cfAudit.getId();
			List<CfAuditServiceTemp> serviceList = form.getServiceList();
			for (CfAuditServiceTemp service : serviceList) {
				CfAuditService cfAuditService = new CfAuditService();
				cfAuditService.setAuditId(id);
				int service_id = csMapper.selectIdByName(service.getServiceName());
				cfAuditService.setServiceId(service_id);
				if (service.getType().equals("create")) {
					if (service.getServiceSize().equals("large")) {
						cfAuditService.setType(3);
					} else if (service.getServiceSize().equals("medium")) {
						cfAuditService.setType(2);
					} else if (service.getServiceSize().equals("small")) {
						cfAuditService.setType(1);
					}
				} else if (service.getType().equals("select")) {
					int service_instance_id = cfServiceInstanceMapper.selectIdByName(service.getServiceInstanceName(),
							service_id);
					cfAuditService.setServiceInstanceId(service_instance_id);
				}
				cfAuditServiceMapper.insertSelective(cfAuditService);
			}

		} catch (Exception e) {
			throw e;
		}
		return ExtJSResponse.successRes();
	}
	
//	@Path("/getone")
//	@GET
//	public ExtJSResponse getone(@QueryParam("id") int id) {
//		Map<String, Object> resMap = new HashMap<String, Object>();
//		CfAudit cfAudit = cfAuditMapper.selectByPrimaryKey(id);
//		AppTemplate templ = atMapper.selectByPrimaryKey(cfAudit.getTemplateId());
//		resMap.put("template", templ);
//		resMap.put("org", (String) session.getAttribute(LoginHandler.ORG));
//		resMap.put("space", (String) session.getAttribute(LoginHandler.SPACE));
//		TemSerExample tsEx = new TemSerExample();
//		tsEx.createCriteria().andTemIdEqualTo(cfAudit.getTemplateId());
//		List<TemSer> tsList = tsMapper.selectByExample(tsEx);
//		CfEnvironment env = ceMapper.selectByPrimaryKey(templ.getEnvId());
//		resMap.put("env", env);
//
//		List<CfService> stoList = new ArrayList<CfService>();
//		List<CfService> anaList = new ArrayList<CfService>();
//		List<CfService> appList = new ArrayList<CfService>();
//		List<CfService> othList = new ArrayList<CfService>();
//
//		if (tsList != null) {
//			for (TemSer ts : tsList) {
//				CfService ser = csMapper.selectByPrimaryKey(ts.getSerId());
//				if (ser != null) {
//					switch (ser.getSerType()) {
//					case 1: {
//						stoList.add(ser);
//						break;
//					}
//					case 2: {
//						anaList.add(ser);
//						break;
//					}
//					case 3: {
//						appList.add(ser);
//						break;
//					}
//					default: {
//						othList.add(ser);
//						break;
//					}
//					}
//				}
//			}
//		} // 添加服务类型的list
//		resMap.put("stoList", stoList);
//		resMap.put("anaList", anaList);
//		resMap.put("appList", appList);
//		resMap.put("othList", othList);
//
//		return ExtJSResponse.successResWithData(resMap);
//	}
}
